package com.cloudcc.cloudframe.net.async;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.json.JSONObject;

import android.text.TextUtils;

import com.cloudcc.cloudframe.model.Jxmedel;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.ServerStatusCode;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.NumberUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.litesuits.android.log.Log;
import com.loopj.android.http.TextHttpResponseHandler;

import de.greenrobot.event.EventBus;

/**
 * @Description: 所有关于 json请求的基类
 * @author wangzhiqiang
 * @date 2015-11-24 下午1:55:57
 * 
 */
public abstract class JsonRequest extends TextHttpResponseHandler implements
		ServerStatusCode {

	private static final String NODE_RESULT = "result";
	private static final String NODE_RESULTCODE = "returnCode";
	private static final String totalCounttag = "totalCount";
	private static final String NODE_RETURNINFO = "returnInfo";

	@Override
	public void onSuccess(int statusCode, Header[] headers,
			String responseString) {
		// 如果 返回的null "" " " data数据参悟
		if (TextUtils.isEmpty(responseString)) {
			handleFailure(ErrorInfo.get(NET_DATA_EXCEPTION));
			return;
		}
		LogUtils.d("responseString", "网络请求数据" + responseString);
		Log.d("responseString", "网络请求数据" + responseString);

		// 初始化json解析器
		JsonParser jsonParser = new JsonParser();
		// 是否成功
		boolean result = false;
		// 成功码
		int retrunCode = -1000;
		// 失败提示
		String returnInfo = "";
		int totalCount = 0;
		JsonObject rootJsonObject = null;
		try {
			JSONObject ob = new JSONObject(responseString);
			// root对象
			rootJsonObject = jsonParser.parse(responseString).getAsJsonObject();
			// 成功
			result = ob.optBoolean(NODE_RESULT);
			retrunCode = NumberUtils.toInt(ob.optString(NODE_RESULTCODE), -1000);
			returnInfo = ob.optString(NODE_RETURNINFO);

//			result = rootJsonObject.get(NODE_RESULT).getAsBoolean();
//			retrunCode = NumberUtils.toInt(rootJsonObject.get(NODE_RESULTCODE)
//					.getAsString(), -1000);
//
//			returnInfo = rootJsonObject.get(NODE_RETURNINFO).getAsString();
			JsonElement meme = rootJsonObject.get("memberinfo");
			try {
				totalCount = NumberUtils.toInt(rootJsonObject.get(totalCounttag)
						.getAsString(), 0);
				Jxmedel jx = new Jxmedel();
				jx.setTotalCount(totalCount);
				EventBus.getDefault().post(jx);
			} catch (Exception e) {
				// TODO: handle exception
			}
			try {
				
				JsonElement url = rootJsonObject.get("url");
				if (url.toString().length() > 5) {
					Jxmedel jx = new Jxmedel();
					jx.setResult(result);
					jx.setUrl(url.toString());
					EventBus.getDefault().post(jx);
					Log.d("urlresult", "url" + url.toString() + "result"
							+ result);
					Log.d("url", "直接走了url不为空" + url + "  cfz" + meme);
				}
			} catch (Exception e) {
				Log.d("urlresult", "解析url错误");
			}

			if (meme == null || ("".equals(meme.toString().trim()))) {
				Log.d("memberinfo", "safd" + meme);

			} else {
				try {
					Log.d("memberinfo", "直接走了meme不为空" + ("".equals(meme))
							+ (meme == null) + meme.toString());
					JsonElement jsonElement2 = rootJsonObject.get("memberinfo");
					Log.d("getfield", "解析下一步");
					JsonArray jsonArrayfield = jsonElement2.getAsJsonArray();
					List<Jxmedel> list = new ArrayList<Jxmedel>();
					for (int i = 0; i < jsonArrayfield.size(); i++) {
						String name = jsonArrayfield.get(i).getAsJsonObject()
								.get("name").toString();
						String value = jsonArrayfield.get(i).getAsJsonObject()
								.get("value").toString();
						Log.d("jsonArrayfield", "meme" + meme + "name" + name
								+ " " + " value" + value);
						Jxmedel jx = new Jxmedel();

						jx.setName(name);
						jx.setValue(value);
						list.add(jx);
						Log.d("jsonArrayfield", "成功获取");
					}
					EventBus.getDefault().post(list);
					Log.d("jsonArrayfield", "成功发送");
				} catch (Exception e) {
					Log.d("meme3", "木有meme失败" + meme);
				}
			}

		} catch (JsonSyntaxException e) {

			handleFailure(ErrorInfo.get(JSON_PARSER_ERROR));
			return;
		} catch (NullPointerException e) {

			handleFailure(ErrorInfo.get(JSON_PARSER_ERROR));
			return;
		} catch (Exception e) {

			handleFailure(ErrorInfo.get(JSON_PARSER_ERROR));
			return;
		}
		if (result && retrunCode == SUCCESS_OK) {
			Log.d("zoudaolenali", "接口請求成功並且發送" + responseString);
			handleSuccess(rootJsonObject, responseString);
		} else {
			Log.d("zoudaolenali", "result" + result);
			handleFailure(ErrorInfo.get(retrunCode, returnInfo));
		}

	}

	@Override
	public void onFailure(int statusCode, Header[] headers,
			String responseString, Throwable throwable) {
		if (throwable != null && StringUtils.isNotBlank(throwable.getMessage())) {
			LogUtils.e("net", throwable.getMessage());
		}
		// 处理检测问题
		if (statusCode == NET_INTERCEPTOR && throwable != null) {
			int errorCode = NumberUtils.toInt(throwable.getMessage(), -100);
			if (errorCode != -100) {
				handleFailure(ErrorInfo.get(errorCode));
			} else {
				handleFailure(new ErrorInfo(NET_DATA_EXCEPTION));
			}
		} else {
			handleFailure(new ErrorInfo(NET_DATA_EXCEPTION));
		}
	}

	/**
	 * 处理 自定义json
	 * 
	 * @param resp
	 */
	public abstract void handleSuccess(JsonObject json, String resp);

	/**
	 * 处理 失败
	 * 
	 * @param e
	 */
	public abstract void handleFailure(ErrorInfo e);

}
